package org.flexharmony.eclipse.properties;

import static org.flexharmony.eclipse.properties.PropertiesConstants.*;

import java.io.File;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jface.preference.IPreferenceStore;
import org.flexharmony.eclipse.HarmonyPlugin;
import org.flexharmony.harmonizer.config.HarmonyConfiguration;

public class ConfigurationBuilder
{
  private IProject project;
  
  public ConfigurationBuilder(IProject project)
  {
    this.project = project;
  }
  
  public HarmonyConfiguration createConfiguration() throws CoreException
  {
    HarmonyConfiguration configuration = new HarmonyConfiguration();
    
    QualifiedName qname = new QualifiedName(HarmonyPlugin.PLUGIN_ID, FLEX_SRC_DIR_NAME);
    String flexSrcDirName = getPropertyString(FLEX_SRC_DIR_NAME);
    
    IFolder flexProjectFolder = project.getFolder(flexSrcDirName);
    
    File flexSrcDir = flexProjectFolder.getLocation().toFile();
    configuration.setFlexSrcDir(flexSrcDir);
    
    boolean additiveSync = Boolean.parseBoolean(getPropertyString(ADDITIVE_SYNC));
    configuration.setAdditiveOnly(additiveSync);
    
    return configuration;
  }

  private String getPropertyString(String name) throws CoreException
  {
    QualifiedName qname = new QualifiedName(HarmonyPlugin.PLUGIN_ID, name);
    String value = project.getPersistentProperty(qname);
    if (value != null)
    {
      return value;
    }
    else
    {
      return getGlobalPreference(name);
    }
  }
  
  private String getGlobalPreference(String name)
  {
    IPreferenceStore prefStore = HarmonyPlugin.getInstance().getPreferenceStore();
    return prefStore.getString(name);
  }
}
